package com.hmall.order.interceptor;

import com.hmall.order.util.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class OrderInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("authorization");
        log.info("当前请求头authorization=======" + authorization);
        if (StringUtils.isEmpty(authorization)) {
            log.warn("非法用户访问！请求路径：{}", request.getRequestURI());
            // 没有用户信息，未登录 403 禁止
            response.setStatus(403);
            return false;
        }
        Long userId = Long.valueOf(authorization);
        //存入threadlocal
        UserUtil.setUserId(userId);
        return true;
    }
}